#include <iostream>

#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include "Thread.hpp"
#include "Comm.hpp"

using namespace ThreadModule;

void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << "local_port\n"
              << std::endl;
}

int Initclient(const std::string &serverip, uint16_t serverport, struct sockaddr_in *server)
{
    // 创建sockfd
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        return -1;
    }
    // 2.0填充struct sockaddr_in 结构

    memset(server,0,sizeof(struct sockaddr_in));
    server->sin_family = AF_INET;
    server->sin_port = htons(serverport);
    server->sin_addr.s_addr = inet_addr(serverip.c_str());
    return sockfd;
}

void recvmessage(int sockfd, std::string name)
{
    while (true)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        char buffer[1024];
        ssize_t n = ::recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            fprintf(stderr, "[%s]%s\n", name.c_str(), buffer);
            // write(fd, buffer, strlen(buffer));
        }
    }
}
void sendmessage(int sockfd, struct sockaddr_in &server, std::string name)
{
    std::string message;
    while (true)
    {
        printf("%s | Enter# ", name.c_str());
        fflush(stdout);
        std::getline(std::cin, message);
        ::sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(-1);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    struct sockaddr_in server;
    int sockfd = Initclient(serverip, serverport, &server);
    if (sockfd == -1)
    {
        std::cerr << "挂了" << std::endl;
        return 1;
    }

    func_t r = std::bind(&recvmessage, sockfd, std::placeholders::_1);
    func_t s = std::bind(&sendmessage, sockfd, server, std::placeholders::_1);

    Thread Recver(r, "recver");
    Thread Sender(s, "sender");

    Recver.Start();
    Sender.Start();

    Recver.Join();
    Sender.Join();

    return 0;
}